/*
 * This file is part of LexiToolsMobile
 *  
 * Author: Jozef Kamycki, Jerzy Wawro
 * ver. 1.00
 * Copyright: Tenar (http://www.tenar.pl)
 *
 * Mobile LexiTools is an open source project; you can redistribute it 
 * and/or modify it under the terms of the license as published -  GPL with 
 * the following modification:  fragments of the code may be not copyleft 
 * (hidden), to protect contents of the dicionaries.
 * In this case the author of non-public fragments of the code is obliged 
 * to make available functionally equivalent code for unprotected dictionaries.
 * 
 * Mobile LexiTools is distributed WITHOUT ANY WARRANTY.
 * See the license for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with LexiToolsMobile (see: gpl.txt); if not - you can find it 
 * on web page http://www.fsf.org/, or write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


package com;

import java.io.*;
import javax.microedition.io.*;

class thrHttpConnection implements Runnable {
    public static final int STATE_INIT = 0;
    public static final int STATE_WAIT = 1;
    public static final int STATE_CONNECT = 2;
    public static final int STATE_RECONNECT = 3;
    public static final int STATE_GET_KEY = 4;
    public static final int STATE_DICT_QUERY = 5;
    public static final int STATE_GET_PRON = 6;
    public static final int STATE_STOP = 9;

    int state;
    int next_state;
    private Object semaphore = new Object();

    String url;
    String kquery;
    String dquery;
    String pquery;
    
    Receiver receiver;
    HttpConnection httpCon = null;
    
    InputStream is = null;
    OutputStream os = null;
    
    public thrHttpConnection(String url, Receiver receiver) {
        state=STATE_INIT;
        next_state=STATE_INIT;
        this.receiver = receiver;
        this.url = url.startsWith("http://") ? url : "http://" + url;
    }

    void close() {
       try {
        if (is != null) {
           is.close();
        }
        if (os != null) {
           os.close();
        }
        if (httpCon != null) {
            httpCon.close();
        }
      } catch (Exception x) {
            x.printStackTrace();
            System.out.println("Exception " + x);
            receiver.failure(url);
      }
     
    }
    
    
    void connect() {
        try {
            httpCon = (HttpConnection) Connector.open(url /*"http://www.lexitools.org/lt.php"*/ /*,Connector.READ_WRITE*/);
            httpCon.setRequestProperty("connection","Keep-Alive");
            httpCon.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            httpCon.setRequestProperty("Content-Language", System.getProperty("microedition.locale"));
            httpCon.setRequestProperty("Keep-Alive","5000");
            httpCon.setRequestMethod(HttpConnection.GET);
              
        } catch (ConnectionNotFoundException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception: " + ioe);
                receiver.failure(url);
        } catch (IOException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception " + ioe);
                receiver.failure(url);
        } catch (Exception x) {
            x.printStackTrace();
            System.out.println("Exception " + x);
            receiver.failure(url);
        }
    }
    
    
     public void prepareRequest( String qurl ) 
        throws IOException

       {
            if (httpCon == null) {
                httpCon = (HttpConnection) Connector.open(qurl);
                httpCon.setRequestProperty("Keep-Alive","5000");
                httpCon.setRequestProperty("connection","Keep-Alive");
                httpCon.setRequestMethod(HttpConnection.POST );
                httpCon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
                httpCon.setRequestProperty("Content-Language", "pl-PL" );
                httpCon.setRequestProperty("Accept", "application/octet-stream" );
            } try {
                  
              } catch (Exception e) {
                System.out.println("Error while web access: "  + e.getMessage());
            }


       }
    

    // uproscic - byte[] -> string[] -> byte[] ????
     
     String executeQuery(String query) {
        StringBuffer b = new StringBuffer();
        
        long len = 0;

        try {
            
            prepareRequest( url+"?"+query ); 
            is = new DataInputStream(httpCon.openInputStream());
            len = httpCon.getLength();
            if (len!=-1) {
                    byte data[] = new byte[(int)len];
                    if (is==null) data[0]=0;
                    else {
                        is.read(data);
                        is.close();
                    }
                    b.append(new String(data));
//                receiver.received(query, data, (int)len, 0);
            }else{
                receiver.failure("couldn't write post data to output stream");
            }
            httpCon.close();
            httpCon=null;
        } catch (Exception e) {
                System.out.println("Error while web access: "  + e.getMessage());
        }
	System.out.println(b.toString());
	return b.toString();
   }
     
     
    void reconnect() {
        close();
        connect();
    }
    
    void do_GetKey() {
        try {
                byte[] data;
                String resp = executeQuery(kquery);
                data = resp.getBytes();
                receiver.received(url, data, data.length, 3);
            } catch (SecurityException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception " + ioe);
                receiver.failure(url);
            } catch (IllegalArgumentException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception " + ioe);
                receiver.failure(url);
            } finally {
            }
    }
    

    void do_DictQuery() {
        try {
                byte[] data;
                String resp = executeQuery(dquery);
                int iLength = resp.length();
                data = resp.getBytes();
                receiver.received(url, data, iLength, 0);
            } catch (SecurityException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception " + ioe);
                receiver.failure(url);
            } catch (IllegalArgumentException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception " + ioe);
                receiver.failure(url);
            } finally {
            }
    }
    
    
    public void do_GetPron() {
        try {
                byte[] data;
                String resp = executeQuery(pquery);
                int iLength = resp.length();
                data = resp.getBytes();
                receiver.received(url, data, iLength, 3);
            } catch (SecurityException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception " + ioe);
                receiver.failure(url);
            } catch (IllegalArgumentException ioe) {
                ioe.printStackTrace();
                System.out.println("Exception " + ioe);
                receiver.failure(url);
            } finally {
            }
    }
    
    public void GetKey(String phone) {
       synchronized(semaphore) {
           kquery="q=key&ph="+phone;
           next_state=STATE_GET_KEY;
           semaphore.notify();
        }
    }
    

    public void DictQuery(String q) {
       synchronized(semaphore) {
           dquery=q;
           next_state=STATE_DICT_QUERY;
           semaphore.notify();
        }
    }
    
    
    public void GetPron(String q) {
       synchronized(semaphore) {
           kquery="q=pron&pl="+q;
           next_state=STATE_GET_PRON;
           semaphore.notify();
        }
    }
    
    
    public void stop()  {
       synchronized(semaphore) {
            next_state=STATE_STOP;
            semaphore.notify();
        }
    }

public void run() {
    synchronized(semaphore) {
         if (state==STATE_INIT) state=STATE_WAIT;
    }
    while (state != STATE_STOP) {
    try {
        synchronized(semaphore) {
            if (state!=next_state) {
                state=next_state;
                next_state=STATE_WAIT;
            }
        }
        if (state==STATE_DICT_QUERY) {
            do_DictQuery();
        }
        else if (state==STATE_GET_KEY) {
            do_GetKey();
        } 
        else if (state==STATE_GET_PRON) {
            do_GetPron();
        }
        else if (state==STATE_WAIT){
            synchronized(semaphore) {
                 semaphore.wait();
           }   
        } else {
           Thread t = Thread.currentThread();
           t.sleep( 2500 );
        }
    }
     catch (InterruptedException e) {
         state=STATE_STOP;
     }
   }
 }
    
}    

public class InternetConnection {
    thrHttpConnection httpConnection;
        
    public InternetConnection(String url, Receiver receiver){        
        httpConnection = new thrHttpConnection(url, receiver); 
        new Thread(httpConnection).start();
    }

    public void Search(String q) {
        httpConnection.DictQuery(q);
    }
}

